package com.sencorsta.ids.account.http.phone;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.account.http.common.EmbedServerVerify;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.service.MysqlService;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.http.HttpHandler;
import com.sencorsta.utils.string.Md5Tools;
import com.sencorsta.utils.string.StringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;

/**
* @description: 忘记密码
* @author TAO
* @date 2019/12/12 18:27
*/
public class ForgetPassWord extends HttpHandler implements RedisService {
    @Override
    public String doPost(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        Out.debug("------------------忘记密码------ForgetPassWord-------------------");
        String phone = params.getString("phone");
        String password = params.getString("password");
        String code = params.getString("code");

        String r_code = R_SYSTEM.hget("code:" + phone, "code");

        //判断code有效
        if (StringUtil.isEmpty(r_code)) {
            return error(ErrorCodeList.CODE_PAST);//redis中没了就代表过期
        }

        //验证码有误  输入的!=REDIS的
        if (!r_code.equals(code)) {
            return error(ErrorCodeList.CODE_ERROR);
        }

        //判断电话号码的用户是否存在
        {
            String sql="SELECT `id` FROM `account` WHERE `phone`=?";
            Object[] args=new Object[]{
                    phone
            };
            JSONArray result=MysqlService.getInstance().select(sql,args);
            if (result.size()==0){
                return error(ErrorCodeList.FORGET_IS_ERROR);
            }
        }


        //开始修改密码
        {
            String sql="UPDATE `account` SET `phone_password`=? WHERE `phone`=?";
            Object[] args=new Object[]{
                    Md5Tools.MD5(password),phone
            };
            if (!MysqlService.getInstance().update(sql,args)){
                return error(ErrorCodeList.LOGIN_ACC_NOT_FIND);
            }
        }
        return success();
    }

    @Override
    public String doGet(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        return doPost(ctx, request, params);
    }

    @Override
    public Boolean getValidate(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        return EmbedServerVerify.Verify(params);
    }

    @Override
    public String getPath() {
        return "/Account/ForgetPassWord";
    }
}
